<?php
namespace app\admin\controller\wechat;

use app\admin\model\Task;
use fast\request;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;
use think\Controller;
use app\common\controller\Backend;

class Index extends Backend
{

    private $appId = 'wxf17196de41200d2d';
    private $appSecret = '9847326749499d7c3d5cdd7850dc95d3';
    private $token = 'vanxtecpeng';
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['*'];


    public function sendMsg($openId,$name,$type,$tel,$task=null,$path=null,$keyword=null)
    {
        $json_template=array(
            'touser'=>$openId,
            'template_id'=>"AbS8pNtJcaL_OoFKweu2cOx3m4bGtSFnpKV3oSVHl6c",
             'url'=>$path,
            'topcolor'=>"#7B68EE",
            'data'=>array(
                'first'=>array('value'=>"您有新的意向客户信息啦，具体信息如下:",'color'=>"#18bc9c"),
                'keyword1'=>array('value'=>$name,'color'=>'#18bc9c'),
                'keyword2'=>array('value'=>$type,'color'=>'#18bc9c'),
                'keyword3'=>array('value'=>'联系方式：'.$tel.',命中关键词：'.$keyword.',任务名称：'.$task,'color'=>'#18bc9c'),
                'keyword4'=>array('value'=>date("Y-m-d H:i:s"),'color'=>'#18bc9c'),
                'remark' =>array('value'=>'意向客户来了，请尽快跟踪哦！点击链接可收听对话，祝您成功','color'=>'#18bc9c'), )
        );

        $reqObj = new request();
        $accessToken = $reqObj->getAccessToken($this->appId, $this->appSecret);
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$accessToken";
        $res=$reqObj->wx_post($url, $json_template);
        //  file_put_contents("log.txt", $res,FILE_APPEND);
        if ($res['errcode']==0){
            return true;
        }else{
            return false;
        }
    }



    public function Index()
    {
//        $this->sendMsg('oA3CO1i2PVs60N_5sA3J-WBalhW4','A',2,3);
//        if($this->checkSignature())
//        {
//            //返回echostr
//            $echostr = $_GET['echostr'];
//            if($echostr)
//            {
//                echo $echostr;
//                exit;
//            }
//        }

        $this->create();
        $this->messageRecord();
    }


    public function checkSignature()
    {
        //先获取到这三个参数
        $signature = $_GET['signature'];
        $nonce = $_GET['nonce'];
        $timestamp = $_GET['timestamp'];

        //把这三个参数存到一个数组里面
        $tmpArr = array($timestamp,$nonce,$this->token);
        //进行字典排序
        sort($tmpArr);

        //把数组中的元素合并成字符串，impode()函数是用来将一个数组合并成字符串的
        $tmpStr = implode($tmpArr);

        //sha1加密，调用sha1函数
        $tmpStr = sha1($tmpStr);
        //判断加密后的字符串是否和signature相等
        if($tmpStr == $signature)
        {

            return true;
        }
        return false;
    }


    public function create()
    {
        $reqObj = new request();

        // get accesstoken
        $accessToken = $reqObj->getAccessToken($this->appId, $this->appSecret);
        $data = [
            'button' => [
                [
                    'type' => 'view',
                    'name' => '进入官网',
                    'url' => 'http://www.vanxtec.com/'
                ],

            ],
        ];

        $this->menu($accessToken,$data);



    }

    /**
     * @param $access_token
     * @param $data
     * @return mixed|string
     * 生成菜单
     */
    public function menu($access_token, $data)
    {
        $req = new request();

        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$access_token";
        $info = $req->wx_post($url, $data);

        if (empty($info)) {
            return "info is null";
        }else{
            return $info;
        }
    }


    /**
     * @param $access_token
     * @param $agentid
     * @return string
     * 删除菜单
     */
    public function delete($access_token, $agentid){

        $req = new request();

        $url="https://qyapi.weixin.qq.com/cgi-bin/menu/delete?access_token=$access_token&agentid=$agentid";

        $req->wx_get($url);

        if (empty($info)) {
            return "info is null";
        }else{
            return $info;
        }
    }


    /**
     * 消息回复
     */

    public function messageRecord()
    {
        $postStr = file_get_contents("php://input");
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();//date('Y-m-d H:i:s', time());
        $msgType = trim($postObj->MsgType);
        $event = property_exists($postObj, "Event") ? strtolower($postObj->Event) : "";


        $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        </xml>";

        if($msgType == "event"){

            $eventKey = trim((string)$postObj->EventKey);


            if($event == "subscribe"){

                $taskId = str_replace('qrscene_','',$eventKey);
                if($taskId){
                    $userInfo = Db::name('task_wx')->where('tid',$taskId)->find();
                    if($userInfo){
                        Db::name('task_wx')
                            ->where('id',$taskId)
                            ->update([
                                'openid'   => (string)$fromUsername
                            ]);
                    }else{
                        Db::name('task_wx')->insert([
                                'openid'   => (string)$fromUsername,
                                'tid'       => $taskId,
                                'created_at'=> date('Y-m-d H:i:s'),
                            ]);
                    }
                }

                $contentStr = "您好，我是万巡智能小X，您可以回复我了解更多."."\n"."回复数字'1',了解智能电话机器人."."\n"."回复数字'2',了解应用场景介绍."."\n"."回复数字'3',了解机器人最新版本讯息. ";
                $msgType = "text";

                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;

            }

            if($event == "scan"){

                if($eventKey){
                    //校验是否订阅过
                    $userInfo = Db::name('task_wx')->where('tid',$eventKey)->find();

                    if($userInfo){//如果订阅过，用新的openid覆盖掉上一个人
                        Db::name('task_wx')
                            ->where('tid',$eventKey)
                            ->update([
                                'openid'   => (string)$fromUsername
                            ]);
                    }else{
                        Db::name('task_wx')->insert([
                            'openid'   => (string)$fromUsername,
                            'tid'       => $eventKey,
                            'created_at'=> date('Y-m-d H:i:s'),
                        ]);
                    }
                }
                $contentStr = '您已成功订阅';
                $msgType = "text";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;

            }



        }


        if($msgType == "text") {

            switch ($keyword) {
                case "1":
                    $contentStr = "您好，月盈智能电话机器人是一款可以替代真人，利用AI技术自动拨打电话的销售与客服专家;根据不同行业，提供不同的个性化外呼服务，提升50%的时间成本，降低80%的人工成本。";
                    break;
                case "2":
                    $contentStr = "月盈机器人可在话术库中自行添加复杂的话术场景，根据上百位不同行业的金牌销售进行资源整合后，月盈将会根据相应的场景和项目切换成不同的行业专家进行相应的销售方式或回答。主营场景包括但不限于：教育培训、汽车出行、医疗健康、金融保险、电商物流、物业房产、文娱旅游、政企服务等。";
                    break;
                case "3":
                    $contentStr = "您好，目前暂无最新版本讯息。";
                    break;
                case "消息":
                    $json_template = array(
                        'touser' => (string)$fromUsername,
                        'template_id' => "AbS8pNtJcaL_OoFKweu2cOx3m4bGtSFnpKV3oSVHl6c",
                        // 'url'=>".$uel.",
                        'topcolor' => "#7B68EE",
                        'data' => array(
                            'first' => array('value' => "您有新的意向客户信息啦，具体信息如下:", 'color' => "#18bc9c"),
                            'keyword1' => array('value' => '这是名称', 'color' => '#18bc9c'),
                            'keyword2' => array('value' => '这是类型', 'color' => '#18bc9c'),
                            'keyword3' => array('value' => '这是提醒内容', 'color' => '#18bc9c'),
                            'keyword4' => array('value' => date("Y-m-d H:i:s"), 'color' => '#18bc9c'),
                            'remark' => array('value' => '友情提示：请尽快跟踪哦，祝您成功！', 'color' => '#18bc9c'),)
                    );

                    $reqObj = new request();
                    $accessToken = $reqObj->getAccessToken($this->appId, $this->appSecret);
                    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$accessToken";
                    $res = $reqObj->wx_post($url, $json_template);
                    //  file_put_contents("log.txt", $res,FILE_APPEND);
                    if ($res['errcode'] == 0) {
                        return '发送成功';
                    } else {
                        return '发送失败';
                    }
                    break;
                default:
                    $contentStr = "对不起,你的内容我会稍后回复";
            }
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            //file_put_contents("log.txt", $resultStr,FILE_APPEND);
            echo $resultStr;
        }


    }



    /*
     * 获取ticket
        expire_seconds:二维码有效期（秒）
        type：二维码类型（临时或永久）
        scene:场景编号
    */
    public function getTicket($taskId)
    {
        $reqObj = new request();
        $accessToken = $reqObj->getAccessToken($this->appId, $this->appSecret);
        $data='{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$taskId.'}}}';
        return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$accessToken,true,"post",$data);

    }

    /*
     *  通过ticket获取二维码
     */
    public function getQRCode($taskId)
    {
        header("Content-type: image/jpeg");
        $content=json_decode($this->getTicket($taskId));
        $ticket=$content->ticket;

        $image=$this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket));

        return $image;

    }


    private function _request($curl,$https=true,$method='get',$data=null)
    {
        $ch=curl_init(); //初始化
        curl_setopt($ch,CURLOPT_URL,$curl);
        curl_setopt($ch,CURLOPT_HEADER,false);//设置不需要头信息
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//获取页面内容，但不输出
        if($https)
        {
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);//不做服务器认证
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//不做客户端认证
        }

        if($method=='post')
        {
            curl_setopt($ch, CURLOPT_POST,true);//设置请求是post方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置post请求数据

        }

        $str=curl_exec($ch);//执行访问
        curl_close($ch);//关闭curl，释放资源
        return $str;
    }

}